package com.numberone.iotplatform.security.services;

import com.numberone.iotplatform.entity.User;
import com.numberone.iotplatform.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 实现 Spring Security 的 UserDetailsService，加载用户信息以进行认证。
 * 所有代码已确认兼容 JDK 1.8。
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    UserRepository userRepository;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<User> users = userRepository.findByUsername(username);
        if (users.isEmpty()) {
            log.error("User not found with username: {}", username);
            throw new UsernameNotFoundException("User Not Found with username: " + username);
        } else if (users.size() > 1) {
            log.error("Multiple users found for username: {}. Found {} users.", username, users.size());
            throw new UsernameNotFoundException("Multiple users found for username: " + username);
        }
        User user = users.get(0);
        log.info("User found: {}", username);
        return UserDetailsImpl.build(user);
    }
}